#include <stdio.h>
#include <stdlib.h>
#include "hashFind.h"

static int hashMod13(Element x) {
	return x % 13;
}

HashTable* initHashTable(size_t n, double factor) {
	HashTable* table = malloc(sizeof(HashTable));
	if (table == NULL) {
		return NULL;
	}
	size_t cnt = (size_t)(n * 1.0 / factor);
	table->data = malloc(sizeof(HashNode *) * cnt);
	table->len = cnt;
	table->hash = hashMod13;
	return table;
}

void releaseHashTable(HashTable *hash_table) {
	HashNode *tmp;
	if (hash_table) {
		for (int i = 0; i < hash_table->len; ++i) {
			while (hash_table->data[i]) {
				tmp = hash_table->data[i];
				hash_table->data[i] = tmp->next;
				free(tmp);
			}
		}
		free(hash_table);
	}
}

void insertData(HashTable *hash_table, Element e) {
	HashNode *node = malloc(sizeof(HashNode));
	node->key = e;
	node->next = NULL;

	int pos = hash_table->hash(e);
	HashNode *p = hash_table->data[pos];
	if (p) {
		node->next = p->next;
		p->next = node;
	} else {
		hash_table->data[pos] = node;
	}
}

int findData(const HashTable *hash_table, Element e) {
	int pos = hash_table->hash(e);
	HashNode *p = hash_table->data[pos];
	while (p) {
		if (p->key == e) {
			return 1;
		}
		p = p->next;
	}
	return 0;
}